<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>串流设置</title>
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --success-color: #4cc9f0;
            --danger-color: #f72585;
            --warning-color: #f8961e;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --border-radius: 12px;
            --box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            color: var(--dark-color);
        }

        .container {
            max-width: 800px;
            margin: 40px auto;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            overflow: hidden;
        }

        header {
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 25px 30px;
            text-align: center;
        }

        h1 {
            font-size: 2rem;
            font-weight: 600;
            letter-spacing: 1px;
        }

        .content {
            padding: 30px;
        }

        .setting-group {
            margin-bottom: 30px;
            padding: 20px;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
            transition: var(--transition);
            border: 1px solid #eef2f7;
        }

        .setting-group:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
        }

        h3 {
            color: var(--primary-color);
            margin-bottom: 15px;
            font-size: 1.3rem;
            border-bottom: 2px solid #eef2f7;
            padding-bottom: 10px;
        }

        label {
            display: block;
            margin-bottom: 10px;
            font-weight: 600;
            color: #495057;
        }

        input[type="range"] {
            width: 100%;
            height: 8px;
            border-radius: 5px;
            background: #e9ecef;
            outline: none;
            -webkit-appearance: none;
        }

        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            width: 22px;
            height: 22px;
            border-radius: 50%;
            background: var(--primary-color);
            cursor: pointer;
            transition: var(--transition);
        }

        input[type="range"]::-webkit-slider-thumb:hover {
            transform: scale(1.2);
            background: var(--secondary-color);
        }

        input[type="number"], input[type="text"], input[type="password"], select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: var(--border-radius);
            font-size: 1rem;
            transition: var(--transition);
            background: #f8f9fa;
        }

        input[type="number"]:focus, input[type="text"]:focus, input[type="password"]:focus, select:focus {
            border-color: var(--primary-color);
            background: white;
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
            outline: none;
        }

        .checkbox-container {
            display: flex;
            align-items: center;
            padding: 10px 0;
        }

        .checkbox-container input[type="checkbox"] {
            width: 20px;
            height: 20px;
            margin-right: 12px;
            cursor: pointer;
            accent-color: var(--primary-color);
        }

        .checkbox-container label {
            margin-bottom: 0;
            cursor: pointer;
            font-weight: normal;
        }

        .value-display {
            margin-top: 10px;
            font-size: 0.9rem;
            color: var(--primary-color);
            font-weight: 600;
        }

        .buttons {
            display: flex;
            justify-content: space-between;
            gap: 15px;
            margin-top: 30px;
            flex-wrap: wrap;
        }

        button {
            flex: 1;
            padding: 14px 20px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: var(--transition);
            min-width: 120px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        button:active {
            transform: translateY(0);
        }

        .save-btn {
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
            color: white;
        }

        .return-btn {
            background: linear-gradient(to right, #6c757d, #495057);
            color: white;
        }

        .logout-btn {
            background: linear-gradient(to right, var(--danger-color), #b5179e);
            color: white;
        }

        @media (max-width: 768px) {
            .container {
                margin: 20px auto;
            }
            
            .content {
                padding: 20px;
            }
            
            .buttons {
                flex-direction: column;
            }
            
            button {
                width: 100%;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>串流设置</h1>
        </header>
        
        <div class="content">
            <div class="setting-group">
                <label for="volume">音量</label>
                <input type="range" id="volume" min="0" max="100" value="50">
                <div class="value-display">当前值: <span id="volume-value">50</span></div>
            </div>
            
            <div class="setting-group">
                <label for="video-code-rate">视频码率 (kbps)</label>
                <input type="number" id="video-code-rate" min="0">
            </div>
            
            <div class="setting-group">
                <label for="audio-code-rate">音频码率 (kbps)</label>
                <input type="number" id="audio-code-rate" min="0">
            </div>
            
            <div class="setting-group">
                <div class="checkbox-container">
                    <input type="checkbox" id="audio-available">
                    <label for="audio-available">音频可用性</label>
                </div>
            </div>
            
            <div class="setting-group">
                <div class="checkbox-container">
                    <input type="checkbox" id="video-available">
                    <label for="video-available">视频可用性</label>
                </div>
            </div>
            
            <div class="setting-group">
                <div class="checkbox-container">
                    <input type="checkbox" id="x-axis-reverse">
                    <label for="x-axis-reverse">X 轴反转</label>
                </div>
            </div>
            
            <div class="setting-group">
                <div class="checkbox-container">
                    <input type="checkbox" id="y-axis-reverse">
                    <label for="y-axis-reverse">Y 轴反转</label>
                </div>
            </div>
            
            <div class="setting-group">
                <label for="offline-time-select">自动离线时间</label>
                <select id="offline-time-select">
                    <option value="never">永不</option>
                    <option value="custom">自定义时间</option>
                </select>
                <input type="number" id="automatic-offline-time" min="0" placeholder="分钟" style="display: none; margin-top: 15px;">
            </div>
            
            <div class="setting-group">
                <h3>TURN服务器设置</h3>
                <label for="turn-server">服务器地址</label>
                <input type="text" id="turn-server" placeholder="例如: turn:turn.xlink.cn:3478">
                
                <label for="turn-username">用户名</label>
                <input type="text" id="turn-username" placeholder="用户名">
                
                <label for="turn-password">密码</label>
                <input type="password" id="turn-password" placeholder="密码">
            </div>
            
            <div class="buttons">
                <button class="return-btn" id="return-btn">返回</button>
                <button class="save-btn" id="save-btn">保存</button>
                <button class="logout-btn" id="logout-btn">退出登录</button>
            </div>
        </div>
    </div>

    <script>
        const API_ENDPOINT = '/api/setting';
        const NEVER_OFFLINE_TIME = 307445734561825860n;

        let originalSettings = {};

        document.addEventListener('DOMContentLoaded', function() {
            const volumeSlider = document.getElementById('volume');
            const volumeValue = document.getElementById('volume-value');
            const offlineTimeSelect = document.getElementById('offline-time-select');
            const offlineTimeInput = document.getElementById('automatic-offline-time');

            volumeSlider.addEventListener('input', function() {
                volumeValue.textContent = this.value;
            });
            
            offlineTimeSelect.addEventListener('change', function() {
                if (this.value === 'custom') {
                    offlineTimeInput.style.display = 'block';
                } else {
                    offlineTimeInput.style.display = 'none';
                }
            });

            getCurrentSettings();

            document.getElementById('return-btn').addEventListener('click', function() {
                if (hasChanges() && !confirm('您有未保存的设置，确定要放弃吗？')) {
                    return;
                }
                window.location.href = '/';
            });
            
            document.getElementById('save-btn').addEventListener('click', saveSettings);
            
            document.getElementById('logout-btn').addEventListener('click', function() {
                if (confirm('确定要退出登录吗？此操作将删除所有设置且不可逆！')) {
                    fetch('/api/logout', {
                        method: 'DELETE'
                    }).then(response => {
                        if (response.ok) {
                            alert('已退出登录，即将返回首页');
                            window.location.href = '/';
                        } else {
                            alert('退出登录失败');
                        }
                    }).catch(error => {
                        console.error('退出登录失败:', error);
                        alert('连接错误，无法退出登录');
                    });
                }
            });
        });

        async function getCurrentSettings() {
            try {
                const response = await fetch(API_ENDPOINT);
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                
                // 获取响应文本，而不是直接解析JSON
                const responseText = await response.text();
                
                // 使用正则表达式将大数字用引号包裹，避免JSON.parse的精度损失
                const modifiedResponseText = responseText.replace(
                    /:\s*307445734561825860\b/g, 
                    ': "307445734561825860"'
                );
                
                // 解析修改后的JSON文本
                const settings = JSON.parse(modifiedResponseText);
                
                originalSettings = settings;
                loadSettings(settings);
            } catch (error) {
                console.error('获取设置失败:', error);
                alert('获取设置失败，请刷新页面重试');
            }
        }

        function loadSettings(settings) {
            document.getElementById('volume').value = settings.Volume;
            document.getElementById('volume-value').textContent = settings.Volume;
            document.getElementById('video-code-rate').value = settings.VideoCodeRate;
            document.getElementById('audio-code-rate').value = settings.AudioCodeRate;
            document.getElementById('audio-available').checked = settings.AudioAvailable;
            document.getElementById('video-available').checked = settings.VideoAvailable;
            document.getElementById('x-axis-reverse').checked = settings.X_Axis_Reverse;
            document.getElementById('y-axis-reverse').checked = settings.Y_Axis_Reverse;
            
            const offlineTimeSelect = document.getElementById('offline-time-select');
            const offlineTimeInput = document.getElementById('automatic-offline-time');
            
            // 将从后端获取的字符串或数字转换为BigInt进行精确比较
            if (BigInt(settings.AutomaticOfflineTime) === NEVER_OFFLINE_TIME) {
                offlineTimeSelect.value = 'never';
                offlineTimeInput.style.display = 'none';
            } else {
                offlineTimeSelect.value = 'custom';
                offlineTimeInput.value = settings.AutomaticOfflineTime;
                offlineTimeInput.style.display = 'block';
            }

            if (settings.TurnServer) {
                document.getElementById('turn-server').value = settings.TurnServer.Server || '';
                document.getElementById('turn-username').value = settings.TurnServer.Username || '';
                document.getElementById('turn-password').value = settings.TurnServer.Password || '';
            } else {
                document.getElementById('turn-server').value = '';
                document.getElementById('turn-username').value = '';
                document.getElementById('turn-password').value = '';
            }
        }

        function hasChanges() {
            const currentVolume = parseInt(document.getElementById('volume').value, 10);
            const currentVideoCodeRate = parseInt(document.getElementById('video-code-rate').value, 10);
            const currentAudioCodeRate = parseInt(document.getElementById('audio-code-rate').value, 10);
            const currentAudioAvailable = document.getElementById('audio-available').checked;
            const currentVideoAvailable = document.getElementById('video-available').checked;
            const currentXAxisReverse = document.getElementById('x-axis-reverse').checked;
            const currentYAxisReverse = document.getElementById('y-axis-reverse').checked;
            
            let currentOfflineTime = null;
            const offlineTimeSelectValue = document.getElementById('offline-time-select').value;
            if (offlineTimeSelectValue === 'never') {
                currentOfflineTime = NEVER_OFFLINE_TIME;
            } else {
                currentOfflineTime = BigInt(document.getElementById('automatic-offline-time').value || 0);
            }
            const originalOfflineTime = BigInt(originalSettings.AutomaticOfflineTime);
            
            const turnServer = document.getElementById('turn-server').value;
            const turnUsername = document.getElementById('turn-username').value;
            const turnPassword = document.getElementById('turn-password').value;

            const originalTurnServer = originalSettings.TurnServer || {};
            const isTurnServerChanged = 
                turnServer !== (originalTurnServer.Server || '') ||
                turnUsername !== (originalTurnServer.Username || '') ||
                turnPassword !== (originalTurnServer.Password || '');
            
            if (currentVolume !== originalSettings.Volume) return true;
            if (currentVideoCodeRate !== originalSettings.VideoCodeRate) return true;
            if (currentAudioCodeRate !== originalSettings.AudioCodeRate) return true;
            if (currentAudioAvailable !== originalSettings.AudioAvailable) return true;
            if (currentVideoAvailable !== originalSettings.VideoAvailable) return true;
            if (currentXAxisReverse !== originalSettings.X_Axis_Reverse) return true;
            if (currentYAxisReverse !== originalSettings.Y_Axis_Reverse) return true;
            if (currentOfflineTime !== originalOfflineTime) return true;
            
            if (isTurnServerChanged) return true;
            
            return false;
        }

        async function saveSettings() {
            const volume = parseInt(document.getElementById('volume').value, 10);
            const videoCodeRate = parseInt(document.getElementById('video-code-rate').value, 10);
            const audioCodeRate = parseInt(document.getElementById('audio-code-rate').value, 10);
            const audioAvailable = document.getElementById('audio-available').checked;
            const videoAvailable = document.getElementById('video-available').checked;
            const xAxisReverse = document.getElementById('x-axis-reverse').checked;
            const yAxisReverse = document.getElementById('y-axis-reverse').checked;
            const offlineTimeSelectValue = document.getElementById('offline-time-select').value;
            const offlineTimeInput = document.getElementById('automatic-offline-time').value;
            
            let automaticOfflineTime;
            if (offlineTimeSelectValue === 'never') {
                automaticOfflineTime = Number(NEVER_OFFLINE_TIME);
            } else {
                if (!offlineTimeInput) {
                    alert('请填写自定义离线时间');
                    return;
                }
                automaticOfflineTime = parseInt(offlineTimeInput, 10);
            }

            const turnServer = document.getElementById('turn-server').value;
            const turnUsername = document.getElementById('turn-username').value;
            const turnPassword = document.getElementById('turn-password').value;
            
            let turnServerData = null;
            if (turnServer || turnUsername || turnPassword) {
                if (turnServer && turnUsername && turnPassword) {
                    if (!turnServer.startsWith('turn:') && !turnServer.startsWith('turns:')) {
                        alert('TURN服务器地址格式不正确，请以turn:或turns:开头');
                        return;
                    }
                    turnServerData = {
                        Server: turnServer,
                        Username: turnUsername,
                        Password: turnPassword
                    };
                } else {
                    alert('TURN服务器设置不完整，请填写服务器地址、用户名和密码');
                    return;
                }
            }
            
            const payload = {
                Volume: volume,
                VideoCodeRate: videoCodeRate,
                AudioCodeRate: audioCodeRate,
                AudioAvailable: audioAvailable,
                VideoAvailable: videoAvailable,
                X_Axis_Reverse: xAxisReverse,
                Y_Axis_Reverse: yAxisReverse,
                AutomaticOfflineTime: automaticOfflineTime,
                TurnServer: turnServerData
            };
            
            try {
                const response = await fetch(API_ENDPOINT, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload)
                });
                
                if (response.ok) {
                    alert('设置已保存');
                    await getCurrentSettings();
                    window.location.href = '/';
                } else {
                    alert('保存设置失败');
                }
            } catch (error) {
                console.error('保存设置失败:', error);
                alert('连接错误，无法保存设置');
            }
        }
    </script>

</body>
</html>